package com.zzw.spring.spel;

import com.zzw.spring.model.User;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.SpelCompilerMode;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.List;

public class SpelHello {

    public static void main(String[] args) {
        testCompiler();
        /*ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression("'hello' + 'world'");
        String message = (String) expression.getValue();
        System.out.println(message);*/
    }

    public static void testCompiler(){
        User user = new User();
        user.setUser_name("hello");
        SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE,SpelHello.class.getClassLoader());
        SpelExpressionParser parser = new SpelExpressionParser(configuration);
        EvaluationContext context = new StandardEvaluationContext(user);
        String expression = "getUser_name()";
        SpelExpression spelExpression = parser.parseRaw(expression);
        System.out.println(spelExpression.getValue(context));
        System.out.println(spelExpression.getValue(context));
    }

    public static String testConcat(){
        ExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression("'Hello world'.concat('!')");
        return (String) expression.getValue();
    }

    public static String testUser(){
        User user = new User();
        user.setUser_name("hello");
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext(user);
        String user_name = (String) parser.parseExpression("user_name").getValue(context);
        return user_name;
    }

    public static Boolean testSimple(){
        Simple simple = new Simple();
        simple.booleanList.add(true);
        StandardEvaluationContext context = new StandardEvaluationContext(simple);
        ExpressionParser parser = new SpelExpressionParser();
        parser.parseExpression("booleanList[0]").setValue(context,"false");
        return simple.booleanList.get(0);
    }
}
class Simple{
    public List<Boolean> booleanList = new ArrayList<>();
}
